package com.project.poetry.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.poetry.common.constant.DictConstant;
import com.project.poetry.service.entity.dto.progress.ContinueProgressDTO;
import com.project.poetry.service.entity.dto.progress.ProgressDTO;
import com.project.poetry.service.entity.po.progress.ProgressPO;
import com.project.poetry.service.entity.po.user.UserPO;
import com.project.poetry.service.mapper.ProgressMapper;
import com.project.poetry.service.service.FlyingFlowerService;
import com.project.poetry.service.service.ProgressService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 进度业务层实现类
 * @author mengxj
 */
@Service
public class ProgressServiceImpl extends ServiceImpl<ProgressMapper, ProgressPO> implements ProgressService {

    @Resource
    private ProgressMapper progressMapper;

    @Resource
    private FlyingFlowerService flyingFlowerService;

    @Override
    public void saveProgress(ProgressDTO progress) {
        Long relationId = progress.getRelationId();
        ProgressPO po = this.progressMapper.selectOne(
                new QueryWrapper<ProgressPO>().lambda().eq(ProgressPO::getRelationId, relationId));
        this.flyingFlowerService.updateFlyingFlower(relationId, 2);
        if(Objects.isNull(po)){
            po = new ProgressPO();
            BeanUtils.copyProperties(progress, po);
            this.progressMapper.insert(po);
        }else{
            po.setHtmlStr(progress.getHtmlStr());
            this.progressMapper.updateById(po);
        }
    }

    @Override
    public ContinueProgressDTO continueProgress(Long relationId, UserPO user) {
        ContinueProgressDTO continueProgress = new ContinueProgressDTO();
        ProgressPO progress = this.progressMapper.selectOne(
                new QueryWrapper<ProgressPO>().lambda().eq(ProgressPO :: getRelationId, relationId));
        //TODO  未保存进度
        continueProgress.setProgress(progress);
        Object relation;
        if (progress.getType() == DictConstant.FLYING_FLOWER) {
            relation = this.flyingFlowerService.continueFlyingFlower(relationId, user);
        } else {
            relation = null;
        }
        continueProgress.setRelation(relation);
        return continueProgress;
    }
}
